// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const MAX_LIMIT = 10

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  
  if (!openid) {
    return {
      success: false,
      message: '请先登录'
    }
  }
  
  try {
    const { page = 1 } = event
    const skip = (page - 1) * MAX_LIMIT
    
    // 获取收藏总数
    const countResult = await db.collection('collections')
      .where({
        _openid: openid
      })
      .count()
    
    const total = countResult.total
    
    // 没有收藏记录
    if (total === 0) {
      return {
        success: true,
        data: {
          list: [],
          page,
          pageSize: MAX_LIMIT,
          total: 0,
          hasMore: false
        }
      }
    }
    
    // 获取收藏列表
    const collectionsRes = await db.collection('collections')
      .where({
        _openid: openid
      })
      .orderBy('createTime', 'desc')
      .skip(skip)
      .limit(MAX_LIMIT)
      .get()
    
    // 处理返回数据
    const list = collectionsRes.data.map(item => {
      // 确保文章信息存在
      if (!item.article) {
        item.article = {
          title: '文章已删除',
          content: '',
          coverImg: '',
          createTime: item.createTime
        }
      }
      return {
        _id: item._id,
        articleId: item.articleId,
        createTime: item.createTime,
        article: item.article
      }
    })
    
    return {
      success: true,
      data: {
        list,
        page,
        pageSize: MAX_LIMIT,
        total,
        hasMore: skip + list.length < total
      }
    }
  } catch (err) {
    console.error('获取收藏列表失败', err)
    return {
      success: false,
      message: '获取收藏列表失败',
      error: err
    }
  }
}